/*
	Copyright (c) 2010 <copyright holders>
	This source code is licensed under The MIT License,
	see the file LICENSE for details.
	*/

#include "MenuNetLogic.hpp"

#include "Game.hpp"
#include "MenuGUI.hpp"
#include "gen/netmsg.pb.h"
#include "WorldManager.hpp" //TODO: get rid of this dep if possible

namespace spelprog2 {
using namespace netmsg;

namespace gui {
namespace net_logic {

void HandleChatMessage::onMessage(MessagePtr msg, const net::NetMessageInfo & info)
{
    ChatMessage * const chatMsg = dynamic_cast<ChatMessage *>(msg.get());

    if (info.origin == net::SERVER_ID) {
        if (!chatMsg->has_sender()) {
            return;
        }

        const std::string name = info.net->getVars().getVar(chatMsg->sender(), "name");
        const std::string line = name + ": " + chatMsg->text();
        gui_.insertChatLine(line);
    }
    else {
        chatMsg->set_sender(info.origin);

        if (chatMsg->receiver() == net::SERVER_ID) {
            info.net->sendToAll(*chatMsg);
        }
        else {
            const net::NetMessageInfo info2 = { info.net, net::SERVER_ID };
            info.net->sendToUser(*chatMsg, chatMsg->receiver());
        }
    }
}


void HandleStartGame::onMessage(MessagePtr msg, const net::NetMessageInfo & info)
{
    const StartGame * const startGame = dynamic_cast<const StartGame *>(msg.get());
    gui_.prepareForPlay(startGame->seed());
}


}; //namespace net_logic
}; //namespace gui
}; //namespace spelprog2